﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;

namespace Virvar.Net
{
    /// <summary>
    /// Нужно закрывать, когда больше не нужен
    /// </summary>
    public class TcpMessager : IMessager
    {
        NetworkStream netStream;
        byte[] buffer = new byte[1024];
        List<byte> receiveBytes = new List<byte>();

        public TcpMessager(NetworkStream netStream)
        {
            this.netStream = netStream;
        }

        public virtual void Send(byte[] data)
        {
            netStream.Write(data, 0, data.Length);
        }

        public virtual byte[] Receive()
        {
            receiveBytes.Clear();
            do
            {
                int bytesCount = netStream.Read(buffer, 0, buffer.Length);
                byte[] tempBytes = new byte[bytesCount];
                Buffer.BlockCopy(buffer, 0, tempBytes, 0, bytesCount);
                receiveBytes.AddRange(tempBytes);
            } while (netStream.DataAvailable);
            return receiveBytes.ToArray();
        }

        public byte[] Receive(ref System.Net.IPEndPoint remoteEP)
        {
            return Receive();
        }

        public void Close()
        {
            netStream.Close();
        }

        ~TcpMessager()
        {
            Close();
        }
    }
}
